package com.wx.timertask;

import com.wx.model.User;
import com.wx.model.templatemessage.Keyworld;
import com.wx.model.templatemessage.WxTemplateMessage;
import com.wx.repository.UserRepository;
import com.wx.service.Impl.WXServiceImpl;
import com.wx.util.BDUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/20 11:06 下午
 * @desc ：上午好 摸鱼人
 */
@Slf4j
@Component
public class FishManTask {
    public static Boolean isRun = false;
    String templateID = "fqt3l5bnkskAfs3tPxaKbk21J24a0d6mP2uBEgDjWmY";
    /**
     * 每天七点
     */
    public static final String  cron1="0 0 10 * * ? " ;
    /**
     * 每分钟一次
     */
    public static final String  cron2="0 * * * * ? " ;

    @Autowired
    UserRepository repository;
    @Autowired
    WXServiceImpl wxService;
    @Autowired
    BDUtil bdUtil;
    @Scheduled(cron = cron1)
    public void dayReminderTaskp(){
        if (isRun){
            return;
        }
        log.info("------摸鱼人定时任务来了");
        isRun = true;
        fish();
        isRun = false;
    }

    private void fish() {

        LocalDateTime today = LocalDateTime.now();
        DayOfWeek dayOfWeek = today.getDayOfWeek();

        if (DayOfWeek.SATURDAY.equals(dayOfWeek) || DayOfWeek.SUNDAY.equals(dayOfWeek) ){
            return;
        }

        String now = today.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
        LocalDateTime nextSaturDay = today.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
        LocalDateTime guoQing = LocalDateTime.of(2021, 10, 1, 00, 00, 00, 00);
        LocalDateTime zhongQiu = LocalDateTime.of(2021, 9, 21, 00, 00, 00, 00);
        LocalDateTime yuanDan = LocalDateTime.of(2022, 1, 1, 00, 00, 00, 00);
        LocalDateTime nian = LocalDateTime.of(2022, 1, 31, 00, 00, 00, 00);


        //获得AccessToken
        String redisToken = wxService.getRedisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String access_token = url.replace("ACCESS_TOKEN", redisToken);

        List<User> users = repository.findUserByFlag();
        for (User user : users) {

            String openID = user.getOpenID();
            if (openID == null || "".equals(openID)){
                continue;
            }

            //构造data参数对象
            //当天日期
            Keyworld keyword0 = new Keyworld(now,"#ffaad5");
            //距离本周周末还有{{keyword1.DATA}}天！
            long l1 = Duration.between(today, nextSaturDay).toDays();
            Keyworld keyword1 = new Keyworld(Long.toString(l1),"#ffaad5");
            //距离中秋假期还有{{keyword2.DATA}}天!
            long l2 = Duration.between(today, zhongQiu).toDays();
            Keyworld keyword2 = new Keyworld(Long.toString(l2),"#ffaad5");
            //国庆
            long l3 = Duration.between(today, guoQing).toDays();
            Keyworld keyword3 = new Keyworld(Long.toString(l3),"#ffaad5");
            //元旦
            long l4 = Duration.between(today, yuanDan).toDays();
            Keyworld keyword4 = new Keyworld(Long.toString(l4),"#ffaad5");
            //春节
            long l5 = Duration.between(today, nian).toDays();
            Keyworld keyword5 = new Keyworld(Long.toString(l5),"#ffaad5");
            //将data参数对象 转化成json
            JSONObject keyword10 = JSONObject.fromObject(keyword0);
            JSONObject keyword11 = JSONObject.fromObject(keyword1);
            JSONObject keyword21 = JSONObject.fromObject(keyword2);
            JSONObject keyword31 = JSONObject.fromObject(keyword3);
            JSONObject keyword41 = JSONObject.fromObject(keyword4);
            JSONObject keyword51 = JSONObject.fromObject(keyword5);
            //构造进  data参数
            JSONObject templateData2 = new JSONObject();
            templateData2.put("keyword0",keyword10);
            templateData2.put("keyword1",keyword11);
            templateData2.put("keyword2",keyword21);
            templateData2.put("keyword3",keyword31);
            templateData2.put("keyword4",keyword41);
            templateData2.put("keyword5",keyword51);
            //构造 请求参数对象
            WxTemplateMessage wxTemplateMessage1 = new WxTemplateMessage(openID, templateID, "https://blog.csdn.net/DreamsArchitects",null);

            //将请求参数对象  转化成 JSON
            JSONObject msgData = JSONObject.fromObject(wxTemplateMessage1);
            msgData.put("data",templateData2.toString());
            System.out.println(msgData);

            String post = httpClient(access_token, "POST", msgData.toString());

            log.info("推送摸鱼人情况："+user.getName()+":"+post);
        }
    }


    public String httpClient(String Url,String RequestMethod,String data){
        StringBuffer sb = null;
        try {
            URL url = new URL(Url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            String s = RequestMethod.toUpperCase();
            httpUrlConn.setRequestMethod(s);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if ("GET".equalsIgnoreCase(RequestMethod)){
                httpUrlConn.connect();
            }else {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"));
                writer.write(data);
                writer.close();
            }
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            sb = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sb);
        log.info(sb.toString());
        return sb.toString();
    }

}
